//
//  LiveCardMessageCell.swift
//  GLUZSwift
//
//  Created by 张国梁 on 2025/7/30.
//
import UIKit
import Reusable
import SnapKit
import ZIM


extension URL {
    func value(for queryKey: String) -> String? {
        guard let components = URLComponents(url: self, resolvingAgainstBaseURL: false),
              let queryItems = components.queryItems else { return nil }
        
        return queryItems.first { $0.name == queryKey }?.value?.removingPercentEncoding
    }
}
extension LiveCardMessageCell: Reusable {}

class LiveCardMessageCell: MessageCell {
    override class var reuseId: String {
        String(describing: LiveCardMessageCell.self)
    }
    
    lazy var markView: UIView = {
        let view = UIView()
        view.backgroundColor = UIColor(hex: "#FFFFFF")
        containerView.addSubview(view)
        return view
    }()
    
    lazy var iconImageView: UIImageView = {
        let imageView = UIImageView()
//        imageView.addRoundedCorners(radius: 8)
        imageView.image = UIImage(named: "live_card_message")
        markView.addSubview(imageView)
        return imageView
    }()
    
    lazy var titleLabel: UILabel = {
        let label = UILabel()
        label.textColor = UIColor(hex: "#333333")
        label.font = .systemFont(ofSize: 14)
        label.numberOfLines = 0;
        markView.addSubview(label)
        return label
    }()
    
    lazy var stateLabel: UILabel = {
        let label = UILabel()
        label.textColor = UIColor(hex: "#333333")
        label.font = .systemFont(ofSize: 12)
        label.numberOfLines = 0;
        markView.addSubview(label)
        return label
    }()
    
    override func setUp() {
        super.setUp()
        
        containerView.addRoundedCorners(radius: 8)
        markView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
        
        iconImageView.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(10)
            make.top.equalTo(10)
            make.size.equalTo(CGSize(width: 80, height: 45))
        }
        
        titleLabel.snp.makeConstraints { make in
            make.left.equalTo(iconImageView.snp.right).offset(10)
            make.right.equalToSuperview().offset(-10)
            make.centerY.equalTo(iconImageView.snp.centerY)
        }
        
        stateLabel.snp.makeConstraints { make in
            make.left.equalTo(10)
            make.right.equalToSuperview().offset(-10)
            make.top.equalTo(iconImageView.snp.bottom).offset(8)
        }
    }
    
    override func setUpLayout() {
        super.setUpLayout()
        updateImageConstraint()
    }
    
    func getFirstLine(_ str: String) -> String {
        let lines = str.components(separatedBy: .newlines)
        return lines.first ?? "" // 若无换行符则返回整个字符串
    }
    
    func extractExhibitorId(from input: String) -> String? {
        // 定义关键标识符
        let prefix = "exhibitorId="
        let separator = "&"
        
        // 查找前缀起始位置
        guard let prefixRange = input.range(of: prefix) else {
            return nil // 未找到前缀
        }
        
        // 计算值起始索引（跳过前缀）
        let valueStartIndex = prefixRange.upperBound
        
        // 查找分隔符位置（从值起始位置开始）
        let substringAfterPrefix = input[valueStartIndex...]
        guard let separatorRange = substringAfterPrefix.range(of: separator) else {
            // 无分隔符时截取到字符串末尾
            return String(substringAfterPrefix)
        }
        
        // 截取中间部分
        let valueEndIndex = separatorRange.lowerBound
        let valueRange = valueStartIndex..<valueEndIndex
        return String(input[valueRange])
    }
    
    private func updateImageConstraint() {
        
        guard messageVM is TextMessageViewModel else {
            xLog("[GoodsMessageCell]: \(String(describing: messageVM))")
            return
        }
        
        if messageVM?.message.zim?.type == .text {
            guard let urlFullStr = messageVM?.message.textContent.content else { return };
            let urlString = getFirstLine(urlFullStr)
            let exhibitorId = extractExhibitorId(from: urlString) ?? ""
            titleLabel.text = "请加入(\(exhibitorId))的会议室"
            stateLabel.text = "Присоединяйтесь к конференц - залу (\(exhibitorId))."
        }
        
        containerView.snp.remakeConstraints { make in
            make.height.equalTo(100)
        }
    }
    
    override func updateContent() {
        super.updateContent()
        guard messageVM is TextMessageViewModel else { return }
        updateImageConstraint()
        
    }
    
}
